package ru.pstu.itas.cps;

import java.util.ArrayList;

import ru.pstu.itas.cps.controls.ActiveElement;
import ru.pstu.itas.cps.controls.ControlElement;
import ru.pstu.itas.cps.controls.Touchable;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;

public class SimulatorView extends View {

	float touchX = 0;
	float touchY = 0;
	ArrayList<ControlElement> controls;

	public SimulatorView(Context context, String panelName, CPSClientConnection connection) {
		super(context);
		PanelConstructor constructor = new PanelConstructor();
		controls = constructor.parseXml(panelName);
		for (ControlElement control : controls)
			if (control instanceof ActiveElement)
				((ActiveElement) control).setOnChangeListener(connection.getListener());
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (controls != null) {
			for (ControlElement control : controls) {
				control.Draw(canvas);
			}
		}
	}

	public void setControlValue(String id, int value) {
		for (ControlElement control : controls)
			if (control instanceof ActiveElement) {
				ActiveElement el = (ActiveElement) control;
				if (el.getId().equalsIgnoreCase(id)) {
					el.setValue(value);
					invalidate();
				}
			}
	}

	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			for (ControlElement control : controls)
				if (control instanceof Touchable)
					((Touchable) control).TouchDown(event.getX(), event.getY());
			break;
		case MotionEvent.ACTION_MOVE:
			for (ControlElement control : controls)
				if (control instanceof Touchable)
					((Touchable) control).TouchMove(event.getX(), event.getY());
			break;
		case MotionEvent.ACTION_UP:
			for (ControlElement control : controls)
				if (control instanceof Touchable)
					((Touchable) control).TouchUp(event.getX(), event.getY());
			break;
		}
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (controls != null) {

			}
		}
		invalidate();
		return true;
	}

}
